<template>
    <!-- 添加全局加载蒙层 -->
    <el-loading v-model:loading="isLoading" :text="loadingText" :spinner="'el-icon-loading'"
        background="rgba(255, 255, 255, 0.8)" :fullscreen="true">
    </el-loading>

    <div v-show="!isLoading" class="student-learning">
        <header class="header">
            <div class="header-inner">
                <h1>互动学习</h1>
                <p v-if="currentCard" class="card-counter">
                    卡片 {{ currentIndex + 1 }} / {{ contents.length }}
                </p>
                <p v-if="lastResponse" class="last-feedback">
                    上次反馈：
                    <span class="highlight">{{ lastResponse.response }}</span> &nbsp;|&nbsp;
                    掌握度：<span class="highlight">{{ lastResponse.mastery_score }}</span> &nbsp;|&nbsp;
                    时长：<span class="highlight">{{ lastResponse.duration }}</span> 分钟
                </p>
            </div>
        </header>
        <main class="main-content">
            <!-- 左侧统计面板 -->
            <aside class="sidebar left-sidebar">
                <h2>今日统计</h2>
                <ul>
                    <li>已学习：{{ studyRecords.length }} 张</li>
                    <li>平均时长：{{ averageDuration }} 分钟</li>
                </ul>
            </aside>

            <!-- 中间学习卡片区域 -->
            <div class="card-area">
                <transition name="card-slide" mode="out-in">
                    <div key="card" v-if="currentIndex < contents.length" class="card-container">
                        <div class="card">
                            <h2 class="card-title">{{ currentCard.title }}</h2>
                            <!-- 一条分割线 -->
                            <hr>
                            </hr>
                            <p class="text">{{ currentCard.text }}</p>
                            <p v-if="currentCard.pinyin" class="pinyin">
                                拼音： 【{{ currentCard.pinyin }}】
                            </p>
                            <p v-if="currentCard.translation" class="translation">
                                翻译： {{ currentCard.translation }}
                            </p>
                            <div v-if="currentCard.definition" class="definition">
                                <strong>释义：</strong>{{ currentCard.definition }}
                            </div>
                            <div v-if="currentCard.quote" class="quote">
                                “{{ currentCard.quote }}”
                                <span v-if="currentCard.quoteAuthor" class="quote-author">
                                    — {{ currentCard.quoteAuthor }}
                                </span>
                            </div>
                            <p v-if="currentCard.example" class="example">
                                例句：{{ currentCard.example }}
                            </p>
                            <!-- <p class="difficulty">难度：{{ currentCard.difficulty }}</p> -->
                        </div>
                        <div class="actions">
                            <button v-for="option in options" :key="option" class="action-button"
                                @click="handleResponse(option)">
                                {{ option }}
                            </button>
                        </div>
                        <!-- 进度条 -->
                        <div class="progress-bar">
                            <div class="progress" :style="{ width: progressPercent + '%' }"></div>
                        </div>
                    </div>
                    <div key="summary" v-else class="summary">
                        <h2>学习总结</h2>
                        <p>共学习 {{ studyRecords.length }} 个内容</p>
                        <ul>
                            <li v-for="record in studyRecords" :key="record.record_id">
                                卡片 {{ record.cardIndex + 1 }}：<span class="highlight">{{ record.response }}</span>
                                (掌握度：<span class="highlight">{{ record.mastery_score }}</span>,
                                时长：<span class="highlight">{{ record.duration }}</span> 分钟)
                            </li>
                        </ul>
                        <button class="restart-button" @click="restart">重新开始</button>
                    </div>
                </transition>
            </div>

            <!-- 右侧学习小贴士 -->
            <aside class="sidebar right-sidebar">
                <h2>学习小贴士</h2>
                <p class="tip">{{ currentTip }}</p>
            </aside>
        </main>
    </div>

</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ApiService, remoteApiClient } from '@/api/apiService';
import { useUserStore } from '@/stores/user';
import { ElLoading } from 'element-plus'; // 新增Element Plus组件引入

// 新增加载状态变量
const isLoading = ref(true);
const loadingText = ref('正在加载学习数据中...');

// 数据部分

const currentIndex = ref(0);
const startTime = ref(Date.now());
const studyRecords = reactive([]);
const recordCounter = ref(0);
const options = ['认识', '熟悉', '模糊', '忘记', '不认识'];
const scoreMapping = {
    '认识': 100,
    '熟悉': 80,
    '模糊': 60,
    '忘记': 20,
    '不认识': 0
};
const lastResponse = ref(null);
const tips = [
    '多读多练，记忆更牢固。',
    '遇到困难不要放弃，加油！',
    '及时复习可以巩固记忆。',
    '注意放松，保持良好心态。',
    '坚持就是胜利，每天一点进步。'
];
// 定义数据
const currentTip = ref(''); // 学习小贴士
const currentStudentId = ref('');  // 当前登录的学生ID
const contents = ref([]); // 学习数据（初始化为空数组）
// 计算属性
const currentCard = computed(() => {
    return contents.value[currentIndex.value] || null;
});
const totalScore = computed(() =>
    studyRecords.reduce((sum, rec) => sum + rec.mastery_score, 0)
);
const averageDuration = computed(() => {
    if (studyRecords.length === 0) return 0;
    const totalDuration = studyRecords.reduce((sum, rec) => sum + rec.duration, 0);
    return Math.round(totalDuration / studyRecords.length);
});
const progressPercent = computed(() => (currentIndex.value / contents.length) * 100);

// 方法
const handleResponse = async (option) => {
    // ====================================================== 熟悉 ===================================================================
    if (option === '认识') {
        console.log('认识 ===》处理中');

        // 获取当前卡片数据
        const currentCardData = contents.value[currentIndex.value];

        // 计算学习时长（分钟）
        const now = Date.now();
        const timeTaken = now - startTime.value;
        const duration = Math.max(1, Math.round(timeTaken / 60000));  // 至少1分钟

        // 提取关键数据
        const taskId = currentCardData.task_id;          // 任务ID
        const contentId = currentCardData.content_id;    // 内容ID
        const type = currentCardData.type.value === '字词' ? '识字' : '背默';               // 学习类型（字词/句子等）
        const mastery_score = scoreMapping[option];      // 掌握度分数（100）

        // 调试输出关键信息
        console.group('学习记录详情');  // 在控制台创建分组
        console.log('📌 任务ID:', taskId);
        console.log('📌 内容ID:', contentId);
        console.log('👨‍🎓 学生ID:', currentStudentId.value);
        console.log('📚 学习类型:', type);
        console.log('⏱️ 学习时长:', duration + '分钟');
        console.log('🎯 掌握度:', mastery_score);
        console.groupEnd();  // 结束分组

        // 封装数据
        const data = {
            task_id: taskId,
            content_id: contentId,
            student_id: currentStudentId.value,
            type: type,
            duration: duration,
            mastery_score: mastery_score
        };
        const response = await ApiService.study_know(data);

        if (response.code === 200) {
            console.log('✅ 数据提交成功');
            // 同时移出队列
            // 移除当前卡片
            contents.value.splice(currentIndex.value, 1);
        }

    }
    // ====================================================== 熟悉 ===================================================================
    if (option == '熟悉') {
        console.log('熟悉 ===》处理中');
        // 获取当前卡片的数据
        const currentCardData = contents.value[currentIndex.value];

        // 获取任务ID和内容ID
        const taskId = currentCardData.task_id; // 假设你的数据中有task_id字段
        const contentId = currentCardData.content_id; // 你的数据中已经有content_id

        console.log('当前任务ID:', taskId);
        console.log('当前内容ID:', contentId);
    }
    if (option == '模糊') {
        console.log('模糊 ===》处理中');
        // 获取当前卡片的数据
        const currentCardData = contents.value[currentIndex.value];

        // 获取任务ID和内容ID
        const taskId = currentCardData.task_id; // 假设你的数据中有task_id字段
        const contentId = currentCardData.content_id; // 你的数据中已经有content_id

        console.log('当前任务ID:', taskId);
        console.log('当前内容ID:', contentId);
    }
    if (option == '忘记') {
        console.log('忘记 ===》处理中');
        // 获取当前卡片的数据
        const currentCardData = contents.value[currentIndex.value];

        // 获取任务ID和内容ID
        const taskId = currentCardData.task_id; // 假设你的数据中有task_id字段
        const contentId = currentCardData.content_id; // 你的数据中已经有content_id

        console.log('当前任务ID:', taskId);
        console.log('当前内容ID:', contentId);
    }
    if (option == '不认识') {
        console.log('不认识 ===》处理中');
        // 获取当前卡片的数据
        const currentCardData = contents.value[currentIndex.value];

        // 获取任务ID和内容ID
        const taskId = currentCardData.task_id; // 假设你的数据中有task_id字段
        const contentId = currentCardData.content_id; // 你的数据中已经有content_id

        console.log('当前任务ID:', taskId);
        console.log('当前内容ID:', contentId);
    }

    const now = Date.now();
    const timeTaken = now - startTime.value;
    const mastery_score = scoreMapping[option];
    const duration = Math.max(1, Math.round(timeTaken / 60000));
    recordCounter.value++;
    const record = {
        record_id: recordCounter.value,
        cardIndex: currentIndex.value,
        response: option,
        mastery_score,
        duration,
        study_time: new Date().toISOString(),
        study_type: currentCard.value.type === '字词' ? '识字' : '背默',
        student_id: 1,
        content_id: currentCard.value.content_id,
        timeTaken
    };
    studyRecords.push(record);
    lastResponse.value = record;
    currentIndex.value++;
    if (currentCard.value) {
        startTime.value = Date.now();
    }
};

const restart = async () => {
    try {
        // 显示加载状态
        isLoading.value = true;
        loadingText.value = '正在重新加载学习数据...';

        // 重置状态
        currentIndex.value = 0;
        startTime.value = Date.now();
        studyRecords.splice(0, studyRecords.length);
        recordCounter.value = 0;
        lastResponse.value = null;

        // 重新获取学习数据
        var userStore = useUserStore();
        var user = userStore.getUser;
        await ApiService.get_current_student_id(user.user_id).then(response => {
            currentStudentId.value = response.data.data.student_id
        });
        // 2.获取学习数据
        console.log('当前学生ID:', currentStudentId.value);
        await ApiService.get_daily_tasks(currentStudentId.value).then(response => {
            console.log('初始化学习数据：', response.data);
            contents.value = response.data.data;
            console.log('学习数据：', contents.value);
        });

        // 随机获取新的学习提示
        await remoteApiClient.get_quote().then(quoteResponse => {
            currentTip.value = quoteResponse.data.anwei;
        });

    } catch (error) {
        console.error('重新开始失败:', error);
        loadingText.value = '重新加载失败，请重试';
    } finally {
        isLoading.value = false;
    }
};
// const randomTip = () => {
//     const randomIndex = Math.floor(Math.random() * tips.length);
//     currentTip.value = tips[randomIndex];
// };

// 生命周期钩子
onMounted(async () => {
    try {
        startTime.value = Date.now();
        // ===========================================初始化每日提示===========================================
        const quoteResponse = await remoteApiClient.get_quote()
            .then((quoteResponse) => {
                // console.log(quoteResponse); // 打印完整的响应对象
                console.log(quoteResponse.data); // 打印返回的数据部分
                // 提取 JSON 数据
                // const jsonString = quoteResponse.data.split('\n').filter(line => line.trim().startsWith('{') && line.trim().endsWith('}')).join('');
                // const jsonData = JSON.parse(jsonString);
                // console.log(jsonData.anwei);

                currentTip.value = quoteResponse.data.anwei;
                console.log(currentTip.value);
                // console.log(quoteResponse.data.anwei);
            })
        // .catch((error) => {
        //     console.error('获取名言失败:', error);
        // });
        // ===========================================初始化学习数据===========================================
        // 1. 获取当前登录的学生ID
        var userStore = useUserStore();
        var user = userStore.getUser;
        await ApiService.get_current_student_id(user.user_id).then(response => {
            currentStudentId.value = response.data.data.student_id
        });
        // 2.获取学习数据
        console.log('当前学生ID:', currentStudentId.value);
        await ApiService.get_daily_tasks(currentStudentId.value).then(response => {
            console.log('初始化学习数据：', response.data);
            contents.value = response.data.data;
            console.log('学习数据：', contents.value);
        });
    } catch (error) {
        console.error('加载数据失败:', error);
        loadingText.value = '数据加载失败，请重试';
    } finally {
        // 确保最终关闭加载状态
        isLoading.value = false;
    }
});


</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
@import url('@/assets/css/studentLeaning.css');
</style>